// -----------------------------------------------------------------------
//  <copyright file="DaprStateStore.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2023 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2023-12-20 14:22</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Domain.States;

using Microsoft.Extensions.Options;


namespace DaprPlus.Dapr.States;

public class DaprStateStore : IStateStore
{
    private readonly DaprClient _daprClient;
    private readonly DaprOptions _options;

    /// <summary>
    /// 初始化一个<see cref="DaprStateStore"/>类型的新实例
    /// </summary>
    public DaprStateStore(DaprClient daprClient, IOptions<DaprOptions> options)
    {
        _daprClient = daprClient;
        _options = options.Value;
    }

    /// <summary>
    /// 保存数据到状态存储
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    /// <param name="key">键</param>
    /// <param name="value">值</param>
    /// <param name="cancellationToken">取消令牌</param>
    /// <returns>保存任务</returns>
    public Task SaveAsync<T>(string key, T value, CancellationToken cancellationToken = default)
    {
        return _daprClient.SaveStateAsync(_options.StateStoreName, key, value, cancellationToken: cancellationToken);
    }

    /// <summary>
    /// 从状态存储中获取数据
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    /// <param name="key">键</param>
    /// <param name="cancellationToken">取消令牌</param>
    /// <returns>获取任务</returns>
    public Task GetAsync<T>(string key, CancellationToken cancellationToken = default)
    {
        return _daprClient.GetStateAsync<T>(_options.StateStoreName, key, cancellationToken: cancellationToken);
    }

    /// <summary>
    /// 从状态存储中删除数据
    /// </summary>
    /// <param name="key">键</param>
    /// <param name="cancellationToken">取消令牌</param>
    /// <returns>删除任务</returns>
    public Task DeleteAsync(string key, CancellationToken cancellationToken = default)
    {
        return _daprClient.DeleteStateAsync(_options.StateStoreName, key, cancellationToken: cancellationToken);
    }
}
